// index.js
var app = getApp();
//此处使用的是腾讯地图的SDK，需要进入其后台UI对其key进行设定
var QQMapWX = require('../../lib/qqmap-wx-jssdk1.1/qqmap-wx-jssdk');
var qqmapsdk;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        "indicatorDots": true,
        "autoplay": true,
        "interval": 5000,
        "animation": null,
        "timer": null,
        "duration": 0,
        "textWidth": 0,
        "wrapWidth": 0,
        "report": "文化和旅游部市场管理司关于印发《旅行社新冠肺炎疫情防控工作指南（第六版）》等指南的通知",
        "city": '',
        "temperature": '',
        navs: [],
        arrays: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this
        that.loadContentData()
        var navs = this.loadNavData();
        that.setData({
            navs: navs
        })
        qqmapsdk = new QQMapWX({
            key: 'C67BZ-43CWX-NSI4V-ZNMPX-RIK3K-ESBTP'
        });
        wx.getSetting({
            withSubscriptions: true,
            success: function (res) {
                if (res.authSetting['scope.userLocation'] == true) {
                    that.locationSelf()
                } else if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    wx.showModal({
                        title: '是否授权位置',
                        content: '需要获取您的地理位置，请确认授权，否则无法相关功能！',
                        success: function (res) {
                            if (res.cancel) {
                                wx.showToast({
                                    title: '您已拒绝授权',
                                })
                            } else if (res.confirm) {
                                wx.openSetting({
                                    success: function (res) {
                                        if (res.authSetting['scope.userLocation'] == true) {
                                            wx.showToast({
                                                title: '授权成功',
                                            })
                                            that.locationSelf()
                                        } else {
                                            wx.showToast({
                                                title: '授权失败',
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                }
            },
            fail: function (err) {
                wx.showModal({
                    title: '提示',
                    content: '未知错误，请重新打开小程序'
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.initAnimation(this.data.text)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.destroyTimer()
        this.setData({
            timer: null
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.destroyTimer()
        this.setData({
            timer: null
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: '翊行',
            path: 'index.wxml',
        }
    },

    destroyTimer() {
        if (this.data.timer) {
            clearTimeout(this.data.timer);
        }
    },

    /**
     * 开启公告字幕滚动动画
     * @param  {String} text 公告内容
     * @return {[type]} 
     */
    initAnimation(text) {
        let that = this
        this.data.duration = 15000
        this.data.animation = wx.createAnimation({
            duration: this.data.duration,
            timingFunction: 'linear'
        })
        let query = wx.createSelectorQuery()
        query.select('.box').boundingClientRect()
        query.select('#report').boundingClientRect()
        query.exec((rect) => {
            that.setData({
                wrapWidth: rect[0].width,
                textWidth: rect[1].width
            }, () => {
                this.startAnimation()
            })
        })
    },

    // 定时器动画
    startAnimation() {
        //reset
        // this.data.animation.option.transition.duration = 0
        const resetAnimation = this.data.animation.translateX(this.data.wrapWidth).step({
            duration: 0
        })
        this.setData({
            animationData: resetAnimation.export()
        })
        // this.data.animation.option.transition.duration = this.data.duration
        const animationData = this.data.animation.translateX(-this.data.textWidth).step({
            duration: this.data.duration
        })
        setTimeout(() => {
            this.setData({
                animationData: animationData.export()
            })
        }, 100)
        const timer = setTimeout(() => {
            this.startAnimation()
        }, this.data.duration)
        this.setData({
            timer
        })
    },

    locationSelf() {
        // console.log("定位了");
        var that = this
        wx.getLocation({
            isHighAccuracy: true,
            success: function (res) {
                // console.log(res)
                let {
                    latitude,
                    longitude
                } = res
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: latitude,
                        longitude: longitude
                    },
                    success: function (res) {
                        //此处打印出location后反向解析出的具体位置，取result中的city
                        // console.log(res.result)
                        that.setData({
                            "city": res.result.ad_info.city
                        })
                        //这里是请求，根据上面location得到的经纬度反向获取得到的城市数据
                        //向百度地图获取该城市的天气信息
                        wx.request({
                            url: 'https://restapi.amap.com/v3/weather/weatherInfo?parameters',
                            data: {
                                key: '876db1210e086b48f0e1142fc7027019',
                                city: res.result.ad_info.adcode,
                            },
                            method: 'GET',
                            success: function (res) {
                                // console.log(res)
                                that.setData({
                                    temperature: res.data.lives[0].temperature
                                })
                            }
                        })
                    },
                    fail: function (res) {
                        console.log(res);
                    }
                })
            }
        })
    },

    message() {
        wx.showModal({
            title: '很抱歉，这里还未完成呢',
        })
    },

    share() {
        var that = this
        console.log(wx.getSetting({}))
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        that.onShareAppMessage()
        wx.showModal({
            title: '提示',
            content: '您可在右上角更多选项中对好友或朋友圈进行分享'
        })
    },

    loadNavData() {
        var navs = [];

        var nav0 = new Object();
        nav0.img = '../../image/icon/huodong.png';
        nav0.name = '活动';
        nav0.fuc = 'toMe'
        navs[0] = nav0;

        var nav1 = new Object();
        nav1.img = '../../image/icon/faxian.png';
        nav1.name = '发现';
        nav1.fuc = 'toDynamic'
        navs[1] = nav1;

        var nav2 = new Object();
        nav2.img = '../../image/icon/dingwei.png';
        nav2.name = '定位';
        nav2.fuc = 'locationSelf'
        navs[2] = nav2;

        var nav3 = new Object();
        nav3.img = '../../image/icon/fenxiang2.png';
        nav3.name = '分享';
        nav3.fuc = 'share'
        navs[3] = nav3;

        return navs
    },

    toDynamic(){
        wx.switchTab({
          url: '../dynamic/dynamic',
        })
    },

    toMe(){
        wx.switchTab({
          url: '../me/me',
        })
    },

    loadContentData: function () {
        var page = this
        wx.request({
            url: 'http://c.3g.163.com/nc/article/list/T1467284926140/0-20.html',
            method: 'get',
            success: function (res) {
                // console.log(res)
                var arrays = []
                let i = 0
                var num = 'arrays' + i
                while (i < 8) {
                    num = new Object();
                    num.title = res.data.T1467284926140[i].title;
                    num.text = res.data.T1467284926140[i].digest;
                    num.img = res.data.T1467284926140[i].imgsrc
                    arrays[i] = num;
                    i = i + 1
                    num.ID = i
                }
                page.setData({
                    arrays: arrays
                })
                // console.log(arrays)
                return arrays
            },
            fail: function (res) {
                console.log(res)
            }
        })
    },
})